<template>
  <div class="fresh-container">
    <!-- 搜索栏 -->
    <div class="search-wrapper">
      <el-input
        v-model="searchText"
        placeholder="请输入名称搜索"
        style="width: 300px"
        clearable
        @keyup.enter="handleSearch">
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="handleSearch">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增生鲜
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="名称" min-width="120" align="center" />
      <el-table-column prop="category" label="种类" width="120" align="center">
        <template #default="scope">
          {{ scope.row.category || '未分类' }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="150" align="center">
        <template #default="scope">
          <div v-if="scope.row.isOnPromotion">
            <div style="text-decoration: line-through; color: #999; font-size: 12px;">
              原价: ¥{{ scope.row.originalPrice?.toFixed(2) }}
            </div>
            <div style="color: #f56c6c; font-weight: bold;">
              现价: ¥{{ scope.row.promotionPrice?.toFixed(2) }}
            </div>
          </div>
          <div v-else>
            ¥{{ scope.row.originalPrice?.toFixed(2) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="stockQuantity" label="库存" width="100" align="center" />
      <el-table-column prop="expiryDate" label="保质期" width="120" align="center" />
      <el-table-column prop="specifications" label="规格" width="120" align="center" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">
            <el-icon><Edit /></el-icon>编辑
          </el-button>
          <el-popconfirm
            title="确定删除该生鲜吗？"
            @confirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button type="danger" link>
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增生鲜' : '编辑生鲜'"
      width="500px"
      @close="resetForm">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="种类" prop="categoryId">
          <el-select
            v-model="formData.categoryId"
            placeholder="请选择种类"
            style="width: 100%"
            @change="handleCategoryChange">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="specifications">
          <el-input v-model="formData.specifications" placeholder="请输入规格" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :precision="2"
            :step="0.1"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="库存" prop="stockQuantity">
          <el-input-number
            v-model="formData.stockQuantity"
            :min="0"
            style="width: 100%" />
        </el-form-item>
        <el-form-item label="保质期" prop="expiryDate">
          <el-date-picker
            v-model="formData.expiryDate"
            type="date"
            placeholder="请选择保质期"
            style="width: 100%"
            value-format="YYYY-MM-DD" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { Search, Plus, Edit, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { get, post } from '@/api/api'
import axios from 'axios'

// 创建API客户端实例
const apiClient = axios.create({
  baseURL: 'http://localhost:8001',
  timeout: 10000
})

// 数据列表
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const searchText = ref('')

// 种类选项
const categoryOptions = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  name: '',
  categoryId: null,
  category: '',
  specifications: '',
  description: '',
  price: 0,
  stockQuantity: 0,
  expiryDate: null
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择种类', trigger: 'change' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  stockQuantity: [{ required: true, message: '请输入库存', trigger: 'blur' }]
}

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    console.log('开始获取生鲜商品数据...')
    const res = await get('/api/fresh-products')
    console.log('生鲜商品列表原始数据:', res)
    console.log('数据类型:', typeof res)
    console.log('是否为数组:', Array.isArray(res))
    console.log('数据长度:', res?.length)

    // 后端直接返回数组，不是分页对象
    if (res && Array.isArray(res)) {
      console.log('处理数组数据，长度:', res.length)
      // 简单的前端分页处理
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      const filteredData = searchText.value
        ? res.filter(item => item.name && item.name.includes(searchText.value))
        : res

      console.log('过滤后数据长度:', filteredData.length)
      console.log('分页范围:', startIndex, '-', endIndex)

      tableData.value = filteredData.slice(startIndex, endIndex)
      total.value = filteredData.length

      console.log('最终表格数据:', tableData.value)
      console.log('总数:', total.value)
    } else {
      console.error('数据格式不正确:', res)
      ElMessage.error('数据格式不正确')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取种类选项（简化为预定义选项）
const fetchCategoryOptions = async () => {
  try {
    // 使用预定义的种类选项
    categoryOptions.value = [
      { id: 1, name: '水果' },
      { id: 2, name: '蔬菜' },
      { id: 3, name: '海鲜' },
      { id: 4, name: '肉类' },
      { id: 5, name: '蛋类' },
      { id: 6, name: '乳制品' },
      { id: 7, name: '其他' }
    ]
  } catch (error) {
    console.error('获取种类列表失败:', error)
    ElMessage.error('获取种类列表失败')
  }
}

// 种类选择改变
const handleCategoryChange = (value) => {
  const category = categoryOptions.value.find(item => item.id === value)
  if (category) {
    formData.category = category.name
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  resetForm()
  // 确保表单被完全重置
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate()
    }
  })
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true

  // 根据category名称找到对应的categoryId
  const categoryOption = categoryOptions.value.find(item => item.name === row.category)

  Object.assign(formData, {
    id: row.id,
    name: row.name,
    categoryId: categoryOption?.id || null,
    category: row.category || '',
    specifications: row.specifications,
    description: row.description,
    price: row.originalPrice || row.price,
    stockQuantity: row.stockQuantity,
    expiryDate: row.expiryDate
  })
}

// 删除
const handleDelete = async (id) => {
  try {
    const res = await apiClient.delete(`/api/fresh-products/${id}`)
    if (res.status === 204 || res.status === 200) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchData()
    }
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 构造提交数据，匹配后端FreshProduct实体
        const submitData = {
          name: formData.name,
          category: formData.category,
          specifications: formData.specifications,
          description: formData.description,
          originalPrice: Number(formData.price),
          stockQuantity: Number(formData.stockQuantity),
          expiryDate: formData.expiryDate
        }

        console.log('提交的数据:', submitData)

        let res
        if (dialogType.value === 'add') {
          res = await apiClient.post('/api/fresh-products', submitData)
        } else {
          res = await apiClient.put(`/api/fresh-products/${formData.id}`, submitData)
        }

        console.log('服务器响应:', res)

        if (res.status === 200 || res.status === 201) {
          ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
          dialogVisible.value = false
          fetchData()
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: null,
    name: '',
    categoryId: null,
    category: '',
    specifications: '',
    description: '',
    price: 0,
    stockQuantity: 0,
    expiryDate: null
  })
}

// 初始化
onMounted(() => {
  fetchCategoryOptions()
  fetchData()
})
</script>

<style scoped>
.fresh-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 